package com.css.zfzx.sjcj.modules.hddcStation.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.excel.handler.ActiveFaultVerifyBaseHandler;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcStation.repository.HddcStationNativeRepository;
import com.css.zfzx.sjcj.modules.hddcStation.repository.HddcStationRepository;
import com.css.zfzx.sjcj.modules.hddcStation.repository.entity.HddcStationEntity;
import com.css.zfzx.sjcj.modules.hddcStation.service.HddcStationService;
import com.css.zfzx.sjcj.modules.hddcStation.viewobjects.HddcStationPageVO;
import com.css.zfzx.sjcj.modules.hddcStation.viewobjects.HddcStationQueryParams;
import com.css.zfzx.sjcj.modules.hddcStation.viewobjects.HddcStationVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zyb
 * @date 2020-11-28
 */
@Service
public class HddcStationServiceImpl implements HddcStationService {

    private final HddcStationRepository hddcStationRepository;
    private final HddcStationNativeRepository hddcStationNativeRepository;
    private final ActiveFaultVerifyBaseHandler activeFaultVerifyBaseHandler;

    @Autowired
    public HddcStationServiceImpl(HddcStationRepository hddcStationRepository,
                                  HddcStationNativeRepository hddcStationNativeRepository,
                                  ActiveFaultVerifyBaseHandler activeFaultVerifyBaseHandler) {
        this.hddcStationRepository = hddcStationRepository;
        this.hddcStationNativeRepository = hddcStationNativeRepository;
        this.activeFaultVerifyBaseHandler = activeFaultVerifyBaseHandler;
    }

    @Override
    public JSONObject queryHddcStations(HddcStationQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcStationPageVO> hddcStationPage = this.hddcStationNativeRepository.queryHddcStations(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcStationPage);
    }


    @Override
    public HddcStationEntity getHddcStation(String id) {
        return this.hddcStationRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcStationEntity saveHddcStation(HddcStationEntity hddcStation) {
        String uuid = UUIDGenerator.getUUID();
        hddcStation.setUuid(uuid);
        hddcStation.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcStation.setCreateTime(now);
        hddcStation.setUpdateTime(now);
        hddcStation.setIsValid(PlatformConstants.Y);
        hddcStation.setQualityinspectionStatus(PlatformConstants.N);
        hddcStation.setExtends10(PlatformConstants.Y);
        this.hddcStationRepository.save(hddcStation);
        return hddcStation;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcStationEntity updateHddcStation(HddcStationEntity hddcStation) {
        HddcStationEntity entity = hddcStationRepository.findById(hddcStation.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcStation);
        hddcStation.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcStation.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcStationRepository.save(hddcStation);
        return hddcStation;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcStations(List<String> ids) {
        List<HddcStationEntity> hddcStationList = this.hddcStationRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcStationList) && hddcStationList.size() > 0) {
            for(HddcStationEntity hddcStation : hddcStationList) {
                hddcStation.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcStation.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcStation.setIsValid("0");
                this.hddcStationRepository.save(hddcStation);
            }
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcStationEntity> hddcStationList = this.hddcStationRepository.queryHddcStationsByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcStationList) && hddcStationList.size() > 0) {
            for(HddcStationEntity hddcStation : hddcStationList) {
                hddcStation.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcStation.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcStation.setIsValid("0");
                this.hddcStationRepository.save(hddcStation);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcStationEntity> hddcStationList = this.hddcStationRepository.queryHddcStationsByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcStationList) && hddcStationList.size() > 0) {
            for(HddcStationEntity hddcStation : hddcStationList) {
                hddcStation.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcStation.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcStation.setIsValid("0");
                this.hddcStationRepository.save(hddcStation);
            }
        }
    }
    
    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcStationQueryParams queryParams, HttpServletResponse response) {
        List<HddcStationEntity> yhDisasterEntities = hddcStationNativeRepository.exportYhDisasters(queryParams);
        List<HddcStationVO> list=new ArrayList<>();
        for (HddcStationEntity entity:yhDisasterEntities) {
            HddcStationVO yhDisasterVO=new HddcStationVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "地震台站-点", "地震台站-点", HddcStationVO.class, "地震台站-点.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(activeFaultVerifyBaseHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcStationVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcStationVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcStationVO yhDisasterVO : result.getFailList()) {
                    String error = "";
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                    returnMsg.append(error);
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcStationVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).append("条记录").toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     */
    public void saveDisasterList(List<HddcStationVO> list) {
        for (HddcStationVO hddcStationVO : list) {
            HddcStationEntity yhDisasterEntity = new HddcStationEntity();
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(hddcStationVO, yhDisasterEntity);
            saveHddcStation(yhDisasterEntity);
        }
    }

}
